#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

const static int gsockfd = -1;
const static uint16_t gport = 8888;

using func_t = std::function<std::string(std::string)>;

class UdpServer
{
public:
    UdpServer(func_t func, uint16_t port = gport)
        : _port(port),
          _sockfd(gsockfd),
          _isrunning(false),
          _func(func)
    {
    }
    void InitServer()
    {
        // 创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket create error!\n");
            exit(0);
        }
        LOG(INFO, "socket success, _sockfd: %d!\n", _sockfd);

        // 2.绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int m = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (m < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(1);
        }
        LOG(INFO, "bind success!\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            // 3.接收客户端的信息
            int n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                inbuffer[n] = 0;

                InetAddr addr(peer);
                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]# " << inbuffer << std::endl;

                // 此时inbuffer里面是一个个单词,调用这个回调函数
                std::string result = _func(inbuffer);

                // 4.把信息返回给客户端
                int x = ::sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
                if (x < 0)
                {
                    LOG(FATAL, "sendto error!\n");
                    break;
                }
            }
            else
            {
                LOG(FATAL, "recvfrom error!\n");
                break;
            }
        }
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;

    func_t _func;
};